using Core;
using FairyGUI;
using Main;
using UnityEngine;

public class JoystickWidget : FGUIWidget<UI_Joystick>
{
    private Vector3 delta;
    private int touchId = -1;
    private float radius;
    private Vector2 startPos;
    private Vector2 initPos;
    protected override void OnInitialize(params object[] args)
    {
        radius = m_root.m_bg.width / 2f;
#if UNITY_EDITOR
        m_root.m_bg.visible = true;
#else
        m_root.m_bg.visible = false;
#endif
        initPos = m_root.m_bg.xy;
        m_root.onTouchBegin.Add(OnTouchBegin);
        m_root.onTouchMove.Add(OnTouchMove);
        m_root.onTouchEnd.Add(OnTouchEnd);
    }

    void OnTouchBegin(EventContext context)
    {
        if (touchId != -1)
            return;
        InputEvent evt = (InputEvent)context.data;
        startPos = m_root.RootToLocal(evt.position, GRoot.inst);//记录点击坐标
        touchId = evt.touchId;
        m_root.m_joystick.SetXY(startPos.x, startPos.y);
        m_root.m_bg.SetXY(startPos.x, startPos.y);
        context.CaptureTouch();
    }

    void OnTouchMove(EventContext context)
    {
        if (touchId == -1)
            return;
        InputEvent evt = (InputEvent)context.data;
        if (evt.touchId != touchId)
            return;
        var pt = m_root.RootToLocal(evt.position, GRoot.inst);
        var offsetPos = pt - startPos;// 获取触摸移动坐标
        if (offsetPos.magnitude > radius)// 移动的距离是否大于摇杆可移动半径
        {
            var angle = Vector2.Angle(offsetPos, Vector2.right);// 获取移动角度
            angle = (offsetPos.y < 0 ? 360 - angle : angle);
            pt.x = radius * Mathf.Cos(angle * Mathf.Deg2Rad);// 计算当前角度可移动最大值
            pt.y = radius * Mathf.Sin(angle * Mathf.Deg2Rad);
            pt += startPos;
            offsetPos = pt - startPos;
        }
        // 归一化移动距离
        delta.Set(offsetPos.x / radius, 0, -offsetPos.y / radius);
        World.GetComponent<InputComponent>().SetDelta(delta);

        m_root.m_joystick.SetXY(pt.x, pt.y);
    }

    void OnTouchEnd(EventContext context)
    {
        touchId = -1;
        m_root.m_joystick.SetXY(initPos.x, initPos.y);
        m_root.m_bg.SetXY(initPos.x, initPos.y);
        World.GetComponent<InputComponent>().SetDelta(Vector3.zero);
    }
}